# -*- coding: utf-8 -*-
import json

from odoo import models, fields, api
from odoo.exceptions import UserError
from odoo.tools import float_round, float_compare, float_is_zero

class MrpProductProduce(models.TransientModel):
    _inherit = "mrp.product.produce"
    _description = "Record Production"

    can_output_qty=fields.Float(string=u'可产出')
    already_output_qty=fields.Float(string=u'已产出')
    # @api.onchange('qty_producing')
    # def onchange_qty_producing(self):
    #     production_id = self.env.context.get('default_production_id') or self.env.context.get('active_id')
    #     if production_id:
    #         production = self.env['mrp.production'].browse(production_id)
    #     if production.exists():
    #         already_output_qty,can_output_qty=self._get_can_do(production)
    #     if float_compare(self.qty_producing,can_output_qty,precision_digits=2)==1:
    #         print(self.qty_producing)
    #         print(self.can_output_qty)
    #         raise UserError('产出数量不能大于领料可产出数量')

    def do_produce(self):
        production_id = self.env.context.get('default_production_id') or self.env.context.get('active_id')
        if production_id:
            production = self.env['mrp.production'].browse(production_id)
        if production.exists():
            already_output_qty, can_output_qty = self._get_can_do(production)
        if float_compare(self.qty_producing,can_output_qty,precision_digits=2)==1:
            print(self.qty_producing)
            print(self.can_output_qty)
            raise UserError('产出数量不能大于领料可产出数量')
        return super(MrpProductProduce, self).do_produce()

    def _get_can_do(self, production):
        main_product_moves = production.move_finished_ids.filtered(
            lambda x: x.product_id.id == production.product_id.id)


        # 可产出-已产出-已报废
        return sum(main_product_moves.mapped('quantity_done')),production.can_output_qty

    @api.model
    def default_get(self, fields):
        res = super(MrpProductProduce, self).default_get(fields)
        production = self.env['mrp.production']
        production_id = self.env.context.get('default_production_id') or self.env.context.get('active_id')
        if production_id:
            production = self.env['mrp.production'].browse(production_id)
        if production.exists():
            if 'can_output_qty' in fields:
                already_output_qty,can_output_qty=self._get_can_do(production)
                res.update({
                    'can_output_qty':can_output_qty,
                    'already_output_qty':already_output_qty,
                })

        return res
